package com.atguigu.flinkWindow;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.java.tuple.Tuple;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.datastream.WindowedStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.windows.GlobalWindow;
import org.apache.flink.util.Collector;

/**
 * 滚动窗口
 * 基于事件个数 对每个key是独立计算的 
 * @author wky
 * @create 2021-07-16-16:48
 */
public class Event_Sliding_Windows {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment senv = StreamExecutionEnvironment.getExecutionEnvironment();
        senv.setParallelism(1);
        DataStreamSource<String> streamSource = senv.socketTextStream("hadoop102", 9999);
        SingleOutputStreamOperator<Tuple2<String, Long>> streamOperator = streamSource.flatMap(new FlatMapFunction<String, Tuple2<String, Long>>() {
            @Override
            public void flatMap(String s, Collector<Tuple2<String, Long>> collector) throws Exception {
                String[] split = s.split(" ");
                for (String s1 : split) {
                    collector.collect(Tuple2.of(s1, 1L));
                }
            }
        });
        KeyedStream<Tuple2<String, Long>, Tuple> keyedStream = streamOperator.keyBy(0);
        WindowedStream<Tuple2<String, Long>, Tuple, GlobalWindow> countWindow = keyedStream.countWindow(5,2);

        countWindow.process(new ProcessWindowFunction<Tuple2<String, Long>, String, Tuple, GlobalWindow>() {
     //todo /*放在这不行 每个滑步都会 对 五条数据重新调用这个方法而这你的无法归零 所以会重复计算   */
//      Long count = 0L;
//            String s = null;
            @Override
            public void process(Tuple tuple, Context context, Iterable<Tuple2<String, Long>> elements, Collector<String> out) throws Exception {
                Long count = 0L;
                String s = null;
                System.out.println("ad.....");
                for (Tuple2<String, Long> element : elements) {
                    //System.out.println(element.f0);
                    System.out.println(element.f1);
                    count=count+1 ;
                    System.out.println(count);

                    s = element.f0 +"-"+ count.toString();
                }
                out.collect(s);
            }
        }).print();
        //countWindow.sum(1).print();
        senv.execute();


    }
}
